
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.net.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

import utility.*;
import database.RecordSearch;
import dbmanager.*;
/**
 *
 * @author Hemant
 * @version * 
 * This is one of the basic servlets we need for operations on database through Web UI.
 * It provides a view for any object 
 */
public class ViewServlet extends HttpServlet implements SingleThreadModel
{
    /**
	 * 
	 */
	private static final long serialVersionUID = -1233237212994658866L;
	GetIdName get = null;
    PrintWriter out = null;
    String username, password;
    
    private void getReport(String ReportId, String reporton)
    {
       // String filepath = Input.MASTERREPORTSPATH+ReportId+"//"+ReportId+"_"+reporton+Input.FILRFORMAT;  
       // System.out.println(filepath);        
                
            //String lines = this.readFile(filepath,ReportId,reporton);
            String [] fileLines = null;
            
            int len = 0;
            try
            {
            	fileLines = this.readFile("",ReportId,reporton);
            	//fileLines = lines.split("\n");
            	len = fileLines.length;
            }
            catch (NullPointerException e) 
            {
            	e.printStackTrace();
			}
            
            out.write("<table width='100%' border='0'");
            String mid = get.getItem(ReportId);
         // writring master and reporton
            out.write("<tr><td><font size='2'><strong>"+mid+" = "+ReportId+"</strong> as <em>"+reporton+"</em></font></td>");
            
            if(reporton.equalsIgnoreCase("mid"))
            {
            	try
            	{
            		out.write("<td align='right'><font size='2'><a href=NewProperty.html?objectname="+mid+">New Property<a></font></td>");
            	}
            	catch (Exception e) 
            	{
					e.printStackTrace();
				}
            }
            
            if( len > 0)
            {
                int midndx = Column.mid_index-1;
                int pidndx = Column.pid_index-1;
                int pvndx = Column.pv_index-1;
                int vtndx = Column.vt_index-1;
                int refndx = Column.ref_index-1;
                
                out.write("</tr><tr></tr>");
                out.write("<tr><td><p><table width='100%' border='1'>");
                
                if(reporton.equalsIgnoreCase("mid"))
                {
                    out.write("<tr><td><font size='2'><strong>Property</strong></font></td><td><font size='2'><strong>Value</strong></font></td><td><font size='2'><strong>Ref</strong></font></td><td><font size='2'></font></td><td><font size='2'></font></td>");
                }
                else
                {
                    out.write("<tr><td><font size='2'><strong>Master</strong></font></td><td><font size='2'><strong>Property</strong></font></td><td><font size='2'><strong>Value</strong></font></td><td><font size='2'><strong>Ref</strong></font></td><td><font size='2'></font></td><td><font size='2'></font></td>");
                }
                
                out.flush();
                
                for(int i=0;i<fileLines.length;i++)
                {
                    String pvval = null,ref = null,pv = null,refval=null, pid = null ;
                    
                    try
                    {
                        //System.out.println(fileLines[i]);                
                        String tabs[] = fileLines[i].split("\t");                                    
                        pid = get.getItem(tabs[pidndx]); 
                        
                        out.write("</tr><tr>");
                        
                        try
                        {
	                        if(!reporton.equalsIgnoreCase("mid"))
	                        {
	                            out.write("<td><font size='2'><a href=ViewServlet?objectname="+get.getItem(tabs[midndx])+">"+get.getItem(tabs[midndx])+"</a></font></td>");
	                        }
	                        
	                        out.write("<td><font size='2'><a href=ViewServlet?objectname="+pid+">"+pid+"</a></font></td>");
                        
                        }
                        catch (ArrayIndexOutOfBoundsException e) 
                        {
                        	out.write("<td><font size='2'></font></td>");	                        
						}
                        
                        if(tabs[pvndx].equals("0"))
                        {
                            pv = tabs[vtndx];
                            pvval = tabs[vtndx];
                            //System.out.println("vtval is "+pvval);

                            out.write("<td><font size='2'>"+pvval+"</font></td>");
                        }
                        else
                        {
                            pv = tabs[pvndx];
                            //System.out.println("pv is "+pv);
                            pvval = get.getItem(tabs[pvndx]);
                            //System.out.println("pvval is "+pvval);

                            out.write("<td><font size='2'><a href=ViewServlet?objectname="+pvval+">"+pvval+"</a></font></td>");
                        }
                                                
                        if(tabs[refndx].equalsIgnoreCase("no$"))
                        {
                            refval = "-";
                            ref = "-";
                            //System.out.println("ref "+ref);                            
                            out.write("<td>"+ref+"</td>");
                        }
                        else if(tabs[refndx].equalsIgnoreCase("0"))
                        {
                            refval = "0";
                            ref = "0";
                           // System.out.println("ref "+ref);                            
                            out.write("<td>0</td>");
                        }
                        else if(tabs[refndx].length()==0)
                        {                            
                            String temp = "-";
                            out.write("<td>"+temp+"</td>");
                        }
                        else
                        {
                            refval = get.getItem(tabs[refndx]);
                            ref = tabs[refndx];
                            //System.out.println("ref "+ref);
                            
                            if(refval.equals("0"))
                            {
                            	out.write("<td><font size='2'>"+tabs[refndx]+"</font></td>");
                            }
                            else
                            	out.write("<td><font size='2'><a href=ViewServlet?objectname="+refval+">"+refval+"</a></font></td>");
                        }                                           
                        
                        if(reporton.equalsIgnoreCase("mid"))
                        {
                            String param = URLEncoder.encode(mid+":"+pid+":"+pvval+":"+refval,"UTF-8");
                            //String abc = "<td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>"; 
                            out.write("<td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>");
                        }
                        else
                        {
                        	ResultSet rs  = DBManager.getSelect("SELECT * FROM property_details where mid = (select pv from property_details where mid="+get.getId(username)+" and pid="+get.getId("webpage")+") and pid="+get.getId(pid)+" and td is null");
                            String param = URLEncoder.encode(get.getItem(tabs[midndx])+":"+pid+":"+pvval+":"+refval,"UTF-8");
                            String pagename = null;
                            while(rs.next())
                            	pagename = get.getItem(rs.getString("PV"))+".html";
                            System.out.println("Pagename is "+pagename);
                            //String abc = "<td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>";
                            //out.write("<td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>");
                            out.write("<td><font size='2'><a href="+pagename+"?objectname="+pvval+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>");
                        }
                    }
                    catch(Exception e)
                    {
                    	e.printStackTrace();
                    	String param = "";
						try 
						{
							param = URLEncoder.encode(mid+":"+pid+":"+pvval+":"+refval,"UTF-8");
						} 
						catch (UnsupportedEncodingException e1) 
						{
							e1.printStackTrace();
						}
						
                        String temp = "-";
                        //String abc = "<td>"+temp+"</td><td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>";
                        out.write("<td><font size='2'><a href=UpdateServlet?linkclicked="+param+">Edit</a></font></td><td><font size='2'><a href=DeleteServlet?linkclicked="+param+">"+"Delete</a></font></td></tr>");
                    }
                }                   
                out.write("</table></p></td></tr>");
                out.flush();
            }
            
            out.write("</table>");
            //out.flush();            
   }
   
   private String[] readFile(String filepath, String mid, String reporton)
   {
	    Hashtable<Object, Object> condition = new Hashtable<Object, Object>();
		condition.put(reporton, mid);
		condition.put("td", "null");
		RecordSearch rs = new RecordSearch();
		rs.setConditionMap(condition);
		String result[] = rs.getArrayFromResultSet();
		return result;
   }
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
   {
        System.out.println("I'm in doGet()");
		get = new GetIdName();
		
		HttpSession session = request.getSession(true);
		username = (String)session.getAttribute("username");
		password = (String)session.getAttribute("password");
		
        String objectselected=request.getParameter("objectname");
        String format = request.getParameter("format");
        out = response.getWriter();
        
        session.setAttribute("objectname", objectselected);
        String object = get.getId(objectselected);
        
        try 
        {
        	if (format.equalsIgnoreCase("html"))
        	{
				RandomAccessFile raf = new RandomAccessFile(Input.LOCATION+objectselected+".html","r");
				String line = null;
				StringBuffer sbr = new StringBuffer();
				
				while((line = raf.readLine())!= null)
					sbr.append(line);
				
				out.write(sbr.toString());	
			}
        	else if(format.equalsIgnoreCase("text"))
        	{
        		out.write("<html><body>");
				out.flush();
				
				synchronized (this) 
				{
					getReport(object, "mid");
					getReport(object, "pid");
					getReport(object, "pv");
					getReport(object, "Ref");
				}
				out.write("</body></html>");
				out.flush();
        	}
		}
        catch (Exception e)
        {
        	//e.printStackTrace();
        	out.write("<html><body>");
			out.flush();
			
			synchronized (this) 
			{
				getReport(object, "mid");
				getReport(object, "pid");
				getReport(object, "pv");
				getReport(object, "Ref");
			}
			out.write("</body></html>");
			out.flush();
		}
        finally
        {
        	get = null;
			out = null;
			//out.close();
        }
    }
               
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
    {
         doGet(request,response);
    }
    
}
